package person.wend.javalearnexample.util.concurrent;

import java.util.List;
import java.util.concurrent.CountedCompleter;
import java.util.concurrent.ForkJoinPool;

public class FileProcessor extends CountedCompleter<Void>{

    private static final int THRESHOLD = 10; // 假设每次处理不超过10个文件
    private List<String> files;
    private final Processor processor;

    public FileProcessor(CountedCompleter<?> parent, List<String> files, Processor processor) {
        super(parent);
        this.files = files;
        this.processor = processor;
    }

    @Override
    public void compute() {
        if (files.size() <= THRESHOLD) {
            // Process the files directly.
            for (String file : files) {
                processor.process(file);
            }
            tryComplete(); // Indicate that this task is done.
        } else {
            // Split the list into two halves and create sub-tasks.
            int mid = files.size() / 2;
            List<String> leftFiles = files.subList(0, mid);
            List<String> rightFiles = files.subList(mid, files.size());

            FileProcessor leftTask = new FileProcessor(this, leftFiles, processor);
            FileProcessor rightTask = new FileProcessor(this, rightFiles, processor);

            setPendingCount(2); // We have two pending tasks to wait for.
            leftTask.fork(); // Start processing the left half asynchronously.
            rightTask.compute(); // Process the right half in this thread.
        }
    }

    @Override
    public void onCompletion(CountedCompleter<?> caller) {
        // This method is called when all sub-tasks are completed.
        System.out.println("All files processed by " + Thread.currentThread().getName());
    }

    // Interface for file processing logic.
    interface Processor {
        void process(String file);
    }

    // Example implementation of the Processor interface.
    static class FilePrinter implements Processor {
        @Override
        public void process(String file) {
            System.out.println(Thread.currentThread().getName() + " is processing: " + file);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        List<String> fileList = List.of("file1.txt", "file2.txt", "file3.txt", "file4.txt",
                "file5.txt", "file6.txt", "file7.txt", "file8.txt",
                "file9.txt", "file10.txt", "file11.txt");

        ForkJoinPool pool = new ForkJoinPool();
        FileProcessor root = new FileProcessor(null, fileList, new FilePrinter());
        pool.invoke(root);
        pool.shutdown();
    }
}
